import React, { Component, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';
import { List, Form, Modal, Input, Popover } from 'antd';
import { connect } from 'dva';
// import { getTimeDistance } from '@/utils/utils';

const FormItem = Form.Item;

const passwordStrength = {
  strong: (
    <font className="strong">
      <FormattedMessage id="app.settings.security.strong" defaultMessage="Strong" />
    </font>
  ),
  medium: (
    <font className="medium">
      <FormattedMessage id="app.settings.security.medium" defaultMessage="Medium" />
    </font>
  ),
  weak: (
    <font className="weak">
      <FormattedMessage id="app.settings.security.weak" defaultMessage="Weak" />
    </font>
  ),
};

@connect(({ user }) => ({
  userInfo: user.userInfo,
}))
@Form.create()
class SecurityView extends Component {
  state = {
    visible: false,
    modalVisible: false,
    help: '',
    confirmLoading: false,
    mailVisible: false,
  }



  getData = () => [
    {
      title: formatMessage({ id: 'app.settings.security.password' }, {}),
      description: (
        <Fragment>
          {formatMessage({ id: 'app.settings.security.password-description' })}：
          {passwordStrength.medium}
        </Fragment>
      ),
      actions: [
        <a onClick={this.showModal}>
          <FormattedMessage id="app.settings.security.modify" defaultMessage="Modify" />
        </a>,
      ],
    },
    // {
    //   title: formatMessage({ id: 'app.settings.security.phone' }, {}),
    //   description: `${formatMessage(
    //     { id: 'app.settings.security.phone-description' },
    //     {}
    //   )}：138****8293`,
    //   actions: [
    //     <a>
    //       <FormattedMessage id="app.settings.security.modify" defaultMessage="Modify" />
    //     </a>,
    //   ],
    // },
    // {
    //   title: formatMessage({ id: 'app.settings.security.question' }, {}),
    //   description: formatMessage({ id: 'app.settings.security.question-description' }, {}),
    //   actions: [
    //     <a>
    //       <FormattedMessage id="app.settings.security.set" defaultMessage="Set" />
    //     </a>,
    //   ],
    // },
    {
      title: formatMessage({ id: 'app.settings.security.email' }, {}),
      description: `${formatMessage(
        { id: 'app.settings.security.email-description' },
        {}
      )}：${this.props.userInfo.mail}`,
      actions: [
        <a onClick={this.showMailModal}>
          <FormattedMessage id="app.settings.security.modify" defaultMessage="Modify" />
        </a>,
      ],
    },
    // {
    //   title: formatMessage({ id: 'app.settings.security.mfa' }, {}),
    //   description: formatMessage({ id: 'app.settings.security.mfa-description' }, {}),
    //   actions: [
    //     <a>
    //       <FormattedMessage id="app.settings.security.bind" defaultMessage="Bind" />
    //     </a>,
    //   ],
    // },
  ];

  checkConfirm = (rule, value, callback) => {
    const { form } = this.props;
    if (value && value !== form.getFieldValue('newPassword')) {
      callback(formatMessage({ id: 'validation.password.twice' }));
    } else {
      callback();
    }
  };

  checkPassword = (rule, value, callback) => {
    const { visible, confirmDirty } = this.state;
    if (!value) {
      this.setState({
        help: formatMessage({ id: 'validation.password.required' }),
        visible: !!value,
      });
      callback('error');
    } else {
      this.setState({
        help: '',
      });
      if (!visible) {
        this.setState({
          visible: !!value,
        });
      }
      if (value.length < 6) {
        callback('error');
      } else {
        const { form } = this.props;
        if (value && confirmDirty) {
          form.validateFields(['confirmNewPassword'], { force: true });
        }
        callback();
      }
    }
  };

  getPasswordStatus = () => {
    const { form } = this.props;
    const value = form.getFieldValue('newPassword');
    if (value && value.length > 9) {
      return 'strong';
    }
    if (value && value.length > 5) {
      return 'medium';
    }
    return 'weak';
  };

  handleOk = () => {
    this.setState({
      // ModalText: 'The modal will be closed after two seconds',
      confirmLoading: true,
    });
    this.handleSubmit()
  }

  handleCancel = () => {
    // console.log('Clicked cancel button');
    this.setState({
      modalVisible: false,
      mailVisible: false,
    });
  }

  showMailModal = () => {
    this.setState({
      mailVisible: true,
    });
  }

  showModal = () => {
    this.setState({
      modalVisible: true,
    });
  }

  handleSubmit = () => {
    // e.preventDefault();
    const { form, dispatch, userInfo } = this.props;
    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        console.log("form", values);
        dispatch({
          type: 'user/setNewPassword',
          payload: {
            id: userInfo.id,
            newPassword: values.newPassword,
          },
          callback: (res) => {
            if (res) {
              this.setState({
                modalVisible: false,
                confirmLoading: false,
              });
            }
          }
        })
      }
    });
  };

  render() {
    const { modalVisible, help, visible, confirmLoading, mailVisible } = this.state;
    const { form: { getFieldDecorator }, } = this.props;
    return (
      <Fragment>
        <List
          itemLayout="horizontal"
          dataSource={this.getData()}
          renderItem={item => (
            <List.Item actions={item.actions}>
              <List.Item.Meta title={item.title} description={item.description} />
            </List.Item>
          )}
        />
        <Modal
          title="新密码"
          visible={modalVisible}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={this.handleCancel}
          maskClosable={false}
        >
          <Form hideRequiredMark>
            <FormItem help={help} label={'新密码'}>
              <Popover
                getPopupContainer={node => node.parentNode}
                content={
                  <div style={{ padding: '4px 0' }}>
                    {passwordStrength[this.getPasswordStatus()]}
                    {/* {this.renderPasswordProgress()} */}
                    <div style={{ marginTop: 10 }}>
                      <FormattedMessage id="validation.password.strength.msg" />
                    </div>
                  </div>
                }
                overlayStyle={{ width: 240 }}
                placement="right"
                visible={visible}
              >
                {getFieldDecorator('newPassword', {
                  rules: [
                    {
                      validator: this.checkPassword,
                    },
                  ],
                })(
                  <Input
                    size="large"
                    type="password"
                    placeholder={formatMessage({ id: 'form.password.placeholder' })}
                  />
                )}
              </Popover>
            </FormItem>
            <FormItem label={'确认密码'}>
              {getFieldDecorator('confirmNewPassword', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'validation.confirm-password.required' }),
                  },
                  {
                    validator: this.checkConfirm,
                  },
                ],
              })(
                <Input
                  size="large"
                  type="password"
                  placeholder={formatMessage({ id: 'form.confirm-password.placeholder' })}
                />
              )}
            </FormItem>
          </Form>
        </Modal>
        <Modal
          title="新邮箱"
          visible={mailVisible}
          // onOk={this.handleOk}
          // confirmLoading={confirmLoading}
          onCancel={this.handleCancel}
          maskClosable={false}
        >
          <Form>
            <FormItem>
              {getFieldDecorator('mail', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'validation.email.required' }),
                  },
                  {
                    type: 'email',
                    message: formatMessage({ id: 'validation.email.wrong-format' }),
                  },
                ],
              })(
                <Input size="large" placeholder={formatMessage({ id: 'form.email.placeholder' })} />
              )}
            </FormItem>
          </Form>
        </Modal>
      </Fragment>
    );
  }
}

export default SecurityView;
